﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Web;
using System.Diagnostics;
using System.Windows.Forms;
using UploadersLib.Helpers;
using Bitly;

namespace hashifyWin
{
    public partial class Form1 : Form
    {
        //--------------------------------------------------------------------------
        //コンストラクタ
        //--------------------------------------------------------------------------
        public Form1()
        {
            InitializeComponent();
        }
        //--------------------------------------------------------------------------
        //起動
        //--------------------------------------------------------------------------
        private void Form1_Load(object sender, EventArgs e)
        {
            string s = "Title";
            //探す文字列が見つかる位置を取得する
            int i = FreeRichTextBox.Text.IndexOf(s);
            if (i > -1)
            {
                FreeRichTextBox.Select(i, s.Length);
                FreeRichTextBox_TextChanged(sender, e);
            }
        }
        //--------------------------------------------------------------------------
        //エンコード
        //--------------------------------------------------------------------------
        public string base64Encode(string data)
        {
            try
            {
                byte[] encData_byte = new byte[data.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Encode" + e.Message);
            }
        }
        //--------------------------------------------------------------------------
        //短縮URL
        //--------------------------------------------------------------------------
        public string GetBitlyURL()
        {
            return API.Bit("moririring", "R_caa2e6271e586a50e71d810fac6fb411", URLTextBox.Text, "Shorten");
        }
        //--------------------------------------------------------------------------
        //テキスト
        //--------------------------------------------------------------------------
        private void FreeRichTextBox_TextChanged(object sender, EventArgs e)
        {
            string strEnc = base64Encode(FreeRichTextBox.Text);
            URLTextBox.Text = "http://hashify.me/" + strEnc;

            int length = strEnc.Length;

            URLCounterToolStripStatusLabel.Text = length.ToString();
            if (length <= 2028)
            {
                URLCounterToolStripStatusLabel.ForeColor = Color.Black;
                TxtSaveToolStripButton.Enabled = true;
                twitterButton.Enabled = true;
                HashifyButton.Enabled = true;
            }
            else if (length <= 2060)
            {
                URLCounterToolStripStatusLabel.ForeColor = Color.Orange;
                TxtSaveToolStripButton.Enabled = false;
                twitterButton.Enabled = false;
                HashifyButton.Enabled = true;
            }
            else
            {
                URLCounterToolStripStatusLabel.ForeColor = Color.Red;
                TxtSaveToolStripButton.Enabled = false;
                twitterButton.Enabled = false;
                HashifyButton.Enabled = false;
            }

        }
        //--------------------------------------------------------------------------
        //セーブ
        //--------------------------------------------------------------------------
        private void SaveToolStripButton_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string shortURL = GetBitlyURL();
                if (Path.GetExtension(saveFileDialog1.FileName).ToUpper() == ".TXT")
                {
                    File.WriteAllText(saveFileDialog1.FileName, FreeRichTextBox.Text + Environment.NewLine + Environment.NewLine + shortURL, System.Text.Encoding.UTF8);
                }
                else
                {
                    string js = "var ie = new ActiveXObject(\"InternetExplorer.Application\");\n";
                    js += "ie.visible = true;\n";
                    js += "ie.navigate(\"http://hashify.me\");\n";
                    js += "while(ie.readystate != 4) {;\n";
                    js += "	WScript.Sleep(1000);\n";
                    js += "};\n";
                    js += "ie.navigate(\"" + shortURL + "\");\n";
                    File.WriteAllText(saveFileDialog1.FileName, js);
                }
            }
        }
        //--------------------------------------------------------------------------
        //バージョン
        //--------------------------------------------------------------------------
        private void VersionToolStripButton_Click(object sender, EventArgs e)
        {
            VersionForm form = new VersionForm();
            form.ShowDialog();
        }
        //--------------------------------------------------------------------------
        //前後に書き消し
        //--------------------------------------------------------------------------
        private bool InsertText(string strStart, string strEnd)
        {
            int start = FreeRichTextBox.SelectionStart;
            int length = FreeRichTextBox.SelectionLength;
            string startText = FreeRichTextBox.Text;

            //選択範囲の中にキーワードがあれば消す
            if (length - strEnd.Length >= 0 &&
                FreeRichTextBox.SelectedText.Length >= strStart.Length &&
                FreeRichTextBox.SelectedText.Substring(0, strStart.Length) == strStart &&
                FreeRichTextBox.SelectedText.Substring(length - strEnd.Length, strEnd.Length) == strEnd)
            {
                FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start + length - strEnd.Length, strEnd.Length);
                FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start, strStart.Length);
                FreeRichTextBox.Select(start, length - strStart.Length - strEnd.Length);
                return true;
            }
            //選択範囲の外にキーワードがあっても消す
            else if (
                start - strStart.Length >= 0 &&
                start + length + strEnd.Length <= FreeRichTextBox.Text.Length &&
                FreeRichTextBox.Text.Substring(start - strStart.Length, strStart.Length) == strStart &&
                FreeRichTextBox.Text.Substring(start + length, strEnd.Length) == strEnd)
            {
                FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start + length, strEnd.Length);
                FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start - strStart.Length, strStart.Length);
                FreeRichTextBox.Select(start - strStart.Length, length);
                return true;
            }
            //それ以外はキーワードを付ける
            else
            {
                string strong = strStart + FreeRichTextBox.SelectedText + strEnd;
                FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start, length);
                FreeRichTextBox.Text = FreeRichTextBox.Text.Insert(start, strong);
                FreeRichTextBox.Select(start + strStart.Length, length);
                return false;
            }
        }
        //--------------------------------------------------------------------------
        //行ごとに書き消し
        //--------------------------------------------------------------------------
        private void InsertLine(bool bDel, string strStart, string strEnd)
        {
            string replece = "";
            //消した
            if (bDel)
            {
                replece = FreeRichTextBox.SelectedText.Replace(strStart, strEnd);
            }
            //書いた
            else
            {
                replece = FreeRichTextBox.SelectedText.Replace(strEnd, strStart);
            }
            int start = FreeRichTextBox.SelectionStart;
            int length = FreeRichTextBox.SelectionLength;
            FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start, length);
            FreeRichTextBox.Text = FreeRichTextBox.Text.Insert(start, replece);
            FreeRichTextBox.Select(start, replece.Length);
        }
        //--------------------------------------------------------------------------
        //wysiwyg
        //--------------------------------------------------------------------------
        private void strongToolStripButton_Click(object sender, EventArgs e)
        {
            InsertText("**", "**");
        }
        private void emphasisToolStripButton_Click(object sender, EventArgs e)
        {
            InsertText("_", "_");
        }
        private void imageToolStripButton_Click(object sender, EventArgs e)
        {
            InsertText("![", "](http://)");
        }
        private void hyperlinkToolStripButton_Click(object sender, EventArgs e)
        {
            InsertText("[", "](http://)");
        }
        private void blockquoteToolStripButton_Click(object sender, EventArgs e)
        {
            bool bDel = InsertText(">", "");
            InsertLine(bDel, "\n>", "\n");
        }
        private void CodeSampleToolStripButton_Click(object sender, EventArgs e)
        {
            bool bDel = InsertText("    ", "    ");
            InsertLine(bDel, "\n    ", "\n");
        }
        private void numberedListToolStripButton_Click(object sender, EventArgs e)
        {
            bool bDel = InsertText(" 1. ", "");
            InsertLine(bDel, "\n 1. ", "\n");
        }
        private void bulletedListToolStripButton_Click(object sender, EventArgs e)
        {
            bool bDel = InsertText(" - ", "");
            InsertLine(bDel, "\n - ", "\n");
        }
        private void headingToolStripButton_Click(object sender, EventArgs e)
        {
            InsertText("#", "");
            InsertLine(true, "\n", " ");
        }
        private void horizontalRuleToolStripButton_Click(object sender, EventArgs e)
        {
            bool bDel = InsertText("- - -", "");

            int start = FreeRichTextBox.SelectionStart;
            int length = FreeRichTextBox.SelectionLength;
            FreeRichTextBox.Text = FreeRichTextBox.Text.Remove(start, length);
            if (bDel == true)
            {
                FreeRichTextBox.Select(start, 0);
            }
            else
            {
                FreeRichTextBox.Select(start - "- - -".Length, "- - -".Length);
            }
         }
        //--------------------------------------------------------------------------
        //ジャンプ
        //--------------------------------------------------------------------------
        private void HashifyButton_Click(object sender, EventArgs e)
        {
            Process.Start(URLTextBox.Text);
        }
        //--------------------------------------------------------------------------
        //QRCode
        //--------------------------------------------------------------------------
        private void QRCodeButton_Click(object sender, EventArgs e)
        {
            string url = GetBitlyURL() + ".qrcode";
            Process.Start(url);
        }
        //--------------------------------------------------------------------------
        //twitter
        //--------------------------------------------------------------------------
        private void twitterButton_Click(object sender, EventArgs e)
        {
            string title = "";
            string url = "";
            int indexofs = FreeRichTextBox.Text.IndexOf('#');
            int indexofn = FreeRichTextBox.Text.IndexOf('\n');
            if (indexofs != -1 && indexofn != -1)
            {
                title = FreeRichTextBox.Text.Substring(indexofs + 1, indexofn);
                title = title.Trim();
            }
            if (title == "")
            {
                url = "http://twitter.com/intent/tweet?text="+ System.Web.HttpUtility.UrlEncode(GetBitlyURL());
            }
            else
            {
                url = "http://twitter.com/intent/tweet?text=" + System.Web.HttpUtility.UrlEncode(title) + "+" + System.Web.HttpUtility.UrlEncode(GetBitlyURL());
            }
            Process.Start(url);


#if zero
            string url = "";
            string xml = "";
            oAuthTwitter oAuth = new oAuthTwitter("nVmWUdUgF4FbSfx39NvPQ", "9yAIWJBRpXQP02MrX28j3KbCWUQohzlFyaeHlPwqNs");

/*
            oAuthTwitter oAuth = new oAuthTwitter("nVmWUdUgF4FbSfx39NvPQ", "9yAIWJBRpXQP02MrX28j3KbCWUQohzlFyaeHlPwqNs");
            url = oAuth.AuthorizationLinkGet();
            TwitterAuthInfo acc = oAuth.AuthInfo;

            Process.Start(url);
            System.Console.WriteLine("Input PIN Code:");
            //string PINCode = System.Console.ReadLine(); 
            
            oAuth.AccessTokenGet(ref acc);
            */




            //oAuth.AuthInfo.UserName = "moririring";
            //oAuth.AuthInfo.Password = "vubb0917";
            oAuth.AuthInfo.Token = "28831830-jclLBCZM3VT9e5Rb2ILWVJnfd0XCF2J2I6R8bvQwh";
            oAuth.AuthInfo.TokenSecret = "n69wEQzshqAUdssiU368xnQTLi4j6F18cchGppFYGwo";


            string encmes = string.Format("status={0:s}", System.Web.HttpUtility.UrlEncode(GetBitlyURL()));
            url = "http://twitter.com/statuses/update.xml";
            xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, encmes);
#endif 
        }

    }
}
